import { createRouter, createWebHashHistory } from 'vue-router'
import Index from '@/views/Index.vue'
// 组件映射
const COMPONENTS = {
	HOME: () => import(/* webpackChunkName: home */ '@/views/Home.vue'),
	USER: () => import(/* webpackChunkName: user */ '@/layout/UserLayout.vue'),
	LOGIN: () => import(/* webpackChunkName: user */ '@/views/user/Login.vue'),
	REGISTER: () => import(/* webpackChunkName: user */ '@/views/user/Register.vue'),
	FORGET: () => import(/* webpackChunkName: user */ '@/views/user/Forget.vue'),
}

const routes = [
	{ path: '/', name: 'index', component: Index, children: [] },
	{
		path: '/user',
		name: 'user',
		component: COMPONENTS.USER,
		children: [
			{
				path: 'login',
				name: 'login',
				component: COMPONENTS.LOGIN,
			},
			{
				path: 'register',
				name: 'register',
				component: COMPONENTS.REGISTER,
			},
			{
				path: 'forget',
				name: 'forget',
				component: COMPONENTS.FORGET,
			},
		],
	},
]

const router = createRouter({
	history: createWebHashHistory(),
	routes,
})
// 处理路由表
export async function FormMenuTORouter(menu) {
	let routes = router.options.routes
	menu.forEach(item => {
		routes[0].children.push(handleMENU(item))
		router.addRoute('index', handleMENU(item))
	})
}
// 将JSON转换成路由对象
function handleMENU(data) {
	let path = '/' + data.url
	if (data.params) {
		path += '/' + data.params
	}
	let filePath = data.url
	if (data.file_path) {
		filePath = data.file_path
	}
	let obj = {
		path: path,
		name: data.id,
		// component: () => require(['@/views/' + filePath], resolve),
		component: () => import('../views/' + filePath + '.vue'),
		meta: { model: data.pid, info: data },
	}
	// 如果有children 递归执行
	if (data.children) {
		obj.children = []
		data.children.forEach(element => {
			obj.children.push(handleMENU(element))
		})
	}
	return obj
}
export function FromMenuToRouter(menu) {
	let routes = router.options.routes
	menu.forEach(item => {
		routes[0].children.push(createRoute(item))
		router.addRoute('index', createRoute(item))
		if (item.children) {
			item.children.forEach(itemChild => {
				routes[0].children.push(createRoute(itemChild))
				router.addRoute('index', createRoute(itemChild))
				if (itemChild.children) {
					itemChild.children.forEach(item3 => {
						routes[0].children.push(createRoute(item3))
						router.addRoute('index', createRoute(item3))
					})
				}
			})
		}
	})
}
function createRoute(data) {
	let path = '/' + data.url
	if (data.params) {
		path += '/' + data.params
	}
	let filePath = data.url
	if (data.file_path) {
		filePath = data.file_path
	}
	return {
		name: data.id,
		path: path,
		component: () => import('../views/' + filePath + '.vue'),
		meta: { model: data.pid, info: data },
	}
}

export default router
